package com.ydche.client;

import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;


abstract class RpcClient implements PooledObjectFactory<TProtocol>{
    private String ip;
    private int port;
    private int timeout;

    public abstract void propertiesSet();
    public abstract TProtocol getConnection();
    public abstract void returnConnection(TProtocol tProtocol);


    @Override
    public PooledObject<TProtocol> makeObject() throws Exception {
//        TSocket tSocket = new TSocket(ip, port, timeout);
//        TTransport tTransport = new TFramedTransport(tSocket);
//        TProtocol protocol = new TBinaryProtocol(tTransport);
        TTransport tTransport = new TSocket(getIp(), getPort(), getTimeout());
        TProtocol tProtocol = new TBinaryProtocol(tTransport);
        tProtocol.getTransport().open();
        return new DefaultPooledObject<>(tProtocol);
    }

    @Override
    public void destroyObject(PooledObject<TProtocol> pooledObject) throws Exception {
        TProtocol tProtocol = pooledObject.getObject();
        if(tProtocol.getTransport().isOpen()){
            tProtocol.getTransport().close();
        }
    }

    @Override
    public boolean validateObject(PooledObject<TProtocol> pooledObject) {
        TProtocol tProtocol = pooledObject.getObject();
        return tProtocol.getTransport().isOpen();
    }

    @Override
    public void activateObject(PooledObject<TProtocol> pooledObject) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<TProtocol> pooledObject) throws Exception {

    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
}
